﻿using Microsoft.Win32;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace DataFilter
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int RedRGB = 0XFF0000;

        private IWorkbook _workBook = null!;

        public MainWindow()
        {
            InitializeComponent();

            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private bool _isFilter = false;

        private async void OnFilterButtonClick(object sender, RoutedEventArgs e)
        {
            if (_isFilter)
            {
                MessageBox.Show("正在处理数据中。");
                return;
            }

            try
            {
                VarietyFileName();
                VarietyOutputFileName();
            }
            catch (InvalidOperationException exception)
            {
                MessageBox.Show(exception.Message, "提示");
                return;
            }
            catch (FileNotFoundException exception)
            {
                MessageBox.Show($"找不到文件{exception.FileName}", "提示");
                return;
            }
            catch (Exception exception)
            {
                MessageBox.Show($"出现了一些小问题，请检查输入参数。", "提示");
                return;
            }

            if (!int.TryParse(DurationTextBox.Text, out var duration))
            {
                MessageBox.Show($"请输入有效的采样持续时间。", "提示");
                return;
            }

            if (!int.TryParse(FrequencyTextBox.Text, out var frequency))
            {
                MessageBox.Show($"请输入有效的采样时间频率。", "提示");
                return;
            }

            if (!int.TryParse(FrequencyErrorTextBox.Text, out var frequencyError))
            {
                MessageBox.Show($"请输入有效的采样频率误差。", "提示");
                return;
            }

            LogTextBlock.Text = string.Empty;
            LogTextBlock.Text += "正在处理Excel数据中...\n";
            _isFilter = true;
            var filter = new ExcelFilter(duration, frequency, frequencyError);
            filter.MissingArgumentCode += Filter_MissingArgumentCode;
            await filter.FilterDataAsync(FileNameTextBox.Text, OutputFileNameTextBox.Text);
            LogTextBlock.Text += $"创建{OutputFileNameTextBox.Text}文件完成。\n";
            await WriteToFileAsync();
            _isFilter = false;
            LogTextBlock.Text += "Excel数据处理完成。\n";
        }

        private List<string> MissingDataList = new List<string>();

        private void Filter_MissingArgumentCode(string obj)
        {
            MissingDataList.Add(obj);
        }

        private async Task WriteToFileAsync()
        {
            using var stream = File.Create(MissingDataFileTextBox.Text);
            using StreamWriter writer = new StreamWriter(stream);

            await Task.Factory.StartNew(() =>
            {
                foreach (var data in MissingDataList)
                {
                    writer.WriteLine(data);
                }
            });
            LogTextBlock.Text += $"创建{MissingDataFileTextBox.Text}文件完成。\n";
        }

        private void SetOutputFileName()
        {
            //var regex = new Regex("(?<=.*-Hello-\\()[0-9]{1,3}(?=\\).xlsx$|\\).xls$)");
            var fileInfo = new FileInfo(FileNameTextBox.Text);
            var fileName = fileInfo.Name.Replace(fileInfo.Extension, "");

            fileName += "-FilterOut";
            var path = Path.Combine(fileInfo.Directory.FullName, Path.ChangeExtension(fileName, fileInfo.Extension));
            OutputFileNameTextBox.Text = path;

            fileName += "-MissingData";
            path = Path.Combine(fileInfo.Directory.FullName, Path.ChangeExtension(fileName, ".csv"));
            MissingDataFileTextBox.Text = path;
        }

        private void VarietyFileName()
        {
            var fileInfo = new FileInfo(FileNameTextBox.Text);

            if (string.IsNullOrWhiteSpace(FileNameTextBox.Text))
            {
                throw new InvalidOperationException("请输入有效的文件名。");
            }
            else
            if (!File.Exists(FileNameTextBox.Text))
            {
                throw new FileNotFoundException("找不到Excel文件", FileNameTextBox.Text);
            }
            else
            if (!string.Equals(fileInfo.Extension, ".xls", StringComparison.OrdinalIgnoreCase)
                && !string.Equals(fileInfo.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException($"不持支处理{fileInfo.Extension}格式的文件。");
            }
        }

        private void VarietyOutputFileName()
        {
            var outFileInfo = new FileInfo(OutputFileNameTextBox.Text);

            if (string.IsNullOrWhiteSpace(OutputFileNameTextBox.Text))
            {
                throw new InvalidOperationException("请输入有效的文件名。");
            }
            else
            if (File.Exists(OutputFileNameTextBox.Text))
            {
                throw new InvalidOperationException($"输出文件已经存在{OutputFileNameTextBox.Text}。");
            }
            else
            if (!string.Equals(outFileInfo.Extension, ".xls", StringComparison.OrdinalIgnoreCase)
             && !string.Equals(outFileInfo.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException($"输出文件不持支处理{outFileInfo.Extension}格式的文件。");
            }

            var missingFileInfo = new FileInfo(MissingDataFileTextBox.Text);

            if (string.IsNullOrWhiteSpace(MissingDataFileTextBox.Text))
            {
                throw new InvalidOperationException("请输入有效的文件名。");
            }
            else
            if (File.Exists(MissingDataFileTextBox.Text))
            {
                throw new InvalidOperationException($"输出文件已经存在{MissingDataFileTextBox.Text}。");
            }
            else
            if (!string.Equals(missingFileInfo.Extension, ".csv", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException($"输出文件不持支处理{outFileInfo.Extension}格式的文件。");
            }
        }

        private void FindFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialot = new OpenFileDialog();
            dialot.Filter = "excel documents(.xlsx) | *.xlsx|excel documents(.xls) | *.xls";
            dialot.ShowDialog();
            FileNameTextBox.Text = dialot.FileName;

            if (File.Exists(FileNameTextBox.Text))
            {
                SetOutputFileName();
            }
        }
    }
}
